/**
 * 
 */
package com.github.phoenics.militia.common.exception;

import java.util.List;
import java.util.Set;

//import javax.validation.ConstraintViolation;
//import javax.validation.ConstraintViolationException;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author Phoenics Chow on 2018年5月18日
 *
 */
public class BaseExceptionHandler {
	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(CommonException.class)
	public BaseResult handleCommonException(CommonException e) {
		return BaseResult.fail(e.getCode(), e.getMessage());
	}
//	@ExceptionHandler(ConstraintViolationException.class)
//	public BaseResult handleCommonException(ConstraintViolationException ex) {
//		Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
//        ConstraintViolation<?> violation = violations.iterator().next();
//        String message = violation.getMessage();
//		return BaseResult.fail(407, message);
//	}//MethodArgumentNotValidException
//	@ExceptionHandler(MethodArgumentNotValidException.class)
//	public BaseResult handleCommonException(MethodArgumentNotValidException ex) {
//		BindingResult bindingResult= ex.getBindingResult();
//		List<ObjectError> errors = bindingResult.getAllErrors();
//		ObjectError err=errors.iterator().next();
//		//ex.getLocalizedMessage()
//		return BaseResult.fail(407, err.getDefaultMessage());
//	}

	@ExceptionHandler(Exception.class)
	public BaseResult handleException(Exception ex) {
		ex.printStackTrace();
		return BaseResult.fail();
	}

//	@ExceptionHandler(value = { AuthorizedException.class })
//	public BaseResult handlerServerError(AuthorizedException ex) {
//		return BaseResult.fail(ex.getCode(), ex.getMsg());
//	}

	@ExceptionHandler(value = { ParamsException.class })
	public BaseResult handlerServerError(ParamsException ex) {
		return BaseResult.fail(ex.getCode(), ex.getMsg());
	}

	@ExceptionHandler(value = { NotFoundException.class })
	public BaseResult handlerServerError(NotFoundException ex) {
		return BaseResult.fail(ex.getCode(), ex.getMsg());
	}

	@ExceptionHandler(value = { ServerException.class })
	public BaseResult handlerServerError(ServerException ex) {
		ex.printStackTrace();
		return BaseResult.fail();
	}

}
